﻿using ECO.Admin.Core.Entities.System;
using ECO.Admin.Core.Entities.User;
using ECO.Admin.Core.EventBus.Dto;
using ECO.Admin.Core.Shared.Const;
using ECO.Admin.Core.Sugar;
using Furion;
using Furion.DependencyInjection;
using Furion.EventBus;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ECO.Admin.Core.EventBus
{
    public class EventSubscriber : IEventSubscriber, ISingleton
    {
        private readonly IDistributedCache _cache;
        private readonly ILogger<EventSubscriber> _logger;
        private readonly Repository<UserLoginLog> _userLoginRepository;

        public EventSubscriber(ILogger<EventSubscriber> logger, IDistributedCache cache)
        {
            _logger = logger;
            _cache = cache;
            _userLoginRepository = App.GetService<Repository<UserLoginLog>>();
        }

        [EventSubscribe(EventSubscriberConst.Login)]
        public async Task UserLogin(EventHandlerExecutingContext context)
        {

            var loginEvent = JsonConvert.DeserializeObject<LoginEvent>(context.Source.Payload.ToString());
            // await _cache.SetStringAsync(todo.EventId, todo.Payload.ToString());
            var userLogin = await _userLoginRepository.GetFirstAsync(x => x.UserId == loginEvent.UserId);
            if (userLogin != null)
            {
                userLogin.LoginTime = loginEvent.LoginTime;

            }
            else
            {
                userLogin = new UserLoginLog()
                {
                    UserId=loginEvent.UserId,
                    LoginTime = loginEvent.LoginTime,
                    IPAddress = loginEvent.IPAddress,
                    
                };
            }
            await _userLoginRepository.InsertOrUpdateAsync(userLogin);
            _logger.LogInformation($"{loginEvent.UserId}登录成功!");
            await Task.CompletedTask;


        }

    }
}
